<?php

namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Validate;

class Index extends Controller
{
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 获取商品规格属性
     * */
    public function getSkusData()
    {
        $input = Request()->param();

        $goods_id = $input['goods_id'];

        if (empty($goods_id)) apiReturn(2, '商品ID缺失');

        $sku_value_list = Db::name('sku_value')->where(['goods_id' => $goods_id])->select();

        //$skus_id_arr：所有属性的id集合
        $skus_id_arr = [];
        if ($sku_value_list) {
            foreach ($sku_value_list as &$val) {
                $val['img'] = getPicture($val['img']);

                $sku_id = explode('-', $val['sku_id']);
                if ($sku_id) {
                    foreach ($sku_id as &$value) {
                        if (!in_array($value, $skus_id_arr)) {
                            $skus_id_arr[] = $value;
                        }
                    }
                }
            }

            $parent_list = Db::name('sku')->distinct(true)->field('pid')->where(['id' => ['IN', $skus_id_arr]])->select();
            $parent_ids = array_column($parent_list, 'pid');
            if ($parent_ids) {
                $sku_list = Db::name('sku')->field('id,name')->where(['id' => ['IN', $parent_ids]])->select();
                if ($sku_list) {
                    foreach ($sku_list as &$v) {
                        $child_list = Db::name('sku')->field('id,name')->where(['pid' => $v['id']])->select();
                        if ($child_list) {
                            foreach ($child_list as &$val) {
                                $val['class'] = '';
                                $val['status'] = false;
                                foreach ($sku_value_list as &$value) {
                                    if (in_array($val['id'], explode('-', $value['sku_id'])) && $value['status']) {
                                        $val['status'] = true;
                                        break;
                                    }
                                }
                            }
                        } else {
                            $child_list = [];
                        }
                        $v['child'] = $child_list;
                    }
                } else {
                    $sku_list = [];
                }
            }
        } else {
            $sku_value_list = [];
        }

        $data = [
            'sku_list' => $sku_list,
            'sku_value_list' => $sku_value_list
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 加入购物车
     * */
    public function addCar()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $goods_id = $input['goods_id'];
        $sku_id = $input['sku_id'];
        $count = $input['count'];

        if (empty($user_id)) apiReturn(2, '操作人ID缺失');
        if (empty($goods_id)) apiReturn(2, '商品ID缺失');
        if (empty($sku_id)) apiReturn(2, '商品规格缺失');
        if ($count <= 0) apiReturn(2, '商品数量错误');

        $car_info = Db::name('admin_goods_car')->where(['user_id' => $user_id, 'goods_id' => $goods_id, 'sku_id' => $sku_id])->find();
        if ($car_info) {
            $res = Db::name('admin_goods_car')->where(['id' => $car_info['id']])->setInc('count', $count);
            if ($res) {
                $count = Db::name('admin_goods_car')->where(['user_id' => $user_id])->count();
                apiReturn(1, '加入购物车成功', $count);
            } else {
                apiReturn(2, '加入购物车失败');
            }
        } else {
            $sku_info = Db::name('sku_value')->where(['sku_id' => $sku_id])->find();
            $img = $sku_info['img'];
            $price = $sku_info['price'];

            $data = [
                'user_id' => $user_id,
                'goods_id' => $goods_id,
                'sku_id' => $sku_id,
                'img' => $img,
                'price' => $price,
                'count' => $count,
                'create_time' => time()
            ];

            $res = Db::name('admin_goods_car')->insert($data);
            if ($res) {
                $count = Db::name('admin_goods_car')->where(['user_id' => $user_id])->count();
                apiReturn(1, '加入购物车成功', $count);
            } else {
                apiReturn(2, '加入购物车失败');
            }
        }
    }

    public function getCarList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '操作人ID缺失');

        $list = Db::name('admin_goods_car')->where(['user_id' => $user_id])->order('id desc')->select();
        if ($list) {
            $all_price = 0;
            foreach ($list as &$v) {
                $all_price += $v['price'] * $v['count'];

                $goods_name = Db::name('goods')->where(['id' => $v['goods_id']])->value('name');
                $v['goods_name'] = $goods_name;
                $v['img'] = getPicture($v['img']);
                $sku_arr = explode('-', $v['sku_id']);
                $sku_name = '';
                foreach ($sku_arr as &$val) {
                    $name = Db::name('sku')->where(['id' => $val])->value('name');
                    if ($sku_name == '') {
                        $sku_name = $name;
                    } else {
                        $sku_name .= ' / ' . $name;
                    }
                }
                $v['sku_name'] = $sku_name;
            }

            $data = [
                'list' => $list,
                'all_price' => sprintf('%.2f', $all_price)
            ];

            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    public function delCarGoods()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '购物车ID缺失');

        $info = Db::name('admin_goods_car')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('admin_goods_car')->where(['id' => $id])->delete();
            if ($res) {
                $list = Db::name('admin_goods_car')->where(['user_id' => $info['user_id']])->select();
                if ($list) {
                    foreach ($list as &$v) {
                        $all_price += $v['price'] * $v['count'];
                    }
                }

                $data = [
                    'count' => count($list),
                    'all_price' => sprintf('%.2f', $all_price)
                ];

                apiReturn(1, '删除成功', $data);
            } else {
                apiReturn(2, '删除失败');
            }

        } else {
            apiReturn(2, '数据不存在或已删除');
        }
    }

    public function goodsCarOrderConfirm()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $all_price = $input['all_price'];

        if (empty($user_id)) apiReturn(2, '用户ID缺失');

        //默认收货地址
        $address_info = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address')->where(['user_id' => $user_id, 'is_default' => 1])->find();
        if ($address_info) {
            $address_info['address'] = getProvinceName($address_info['province_id']) . getCityName($address_info['city_id']) . getAreaName($address_info['area_id']) . $address_info['address'];
        }

        //优惠券列表
        $coupon_list = Db::name('user_coupon')->field('id,coupon_name,full_price,face_price')->where(['user_id' => $user_id, 'is_del' => 0, 'full_price' => ['elt', $all_price], 'status' => 1])->order('expire_time asc')->select();

        // 运费模板信息
        $freight_info = Db::name('freight')->field('id,init_count,init_count_price,inc_count,inc_count_price,diff_freight')->where(['type' => 1])->find();

        $data = [
            'address' => $address_info ? : [],
            'freight_info' => $freight_info,
            'coupon_list' => $coupon_list ? : [],
        ];
        apiReturn(1, '获取数据成功', $data);
    }

    public function addGoodsCarOrder()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $operation_id = cookie('id');
        $coupon_id = $input['coupon_id'];
        $all_price = $input['all_price'];
        $freight_price = $input['freight_price'] ? : 0;
        $pay_price = $input['pay_price'];
        $address_id = $input['address_id'];
        $pay_type = 1;

        if (empty($operation_id)) apiReturn(2, '操作者ID缺失');
        if (empty($user_id)) apiReturn(2, '请选择下单客户');
        if (empty($all_price) || empty($pay_price)) apiReturn(2, '商品金额错误');
        if (empty($address_id)) apiReturn(2, '请选择收货地址');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');

        $time = time();

        Db::startTrans();
        try {
            $car_list = Db::name('admin_goods_car')->field('id,goods_id,price,sku_id,count')->where(['user_id' => $operation_id])->select();

            if ($car_list) {
                $address_info = Db::name('address')->where(['id' => $address_id])->find();
                foreach ($car_list as &$v) {
                    $goods_info = Db::name('goods')->field('id,name')->where(['id' => $v['goods_id']])->find();

                    $sku_info = Db::name('sku_value')->where(['goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']])->find();
                    if ($sku_info) {
                        if ($v['count'] > $sku_info['stock']) apiReturn(2, $goods_info['name'] . '库存不足');
                    } else {
                        apiReturn(2, $goods_info['name'] . '属性不存在或已删除');
                    }

                    $sku_info = Db::name('sku_value')->where(['goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']])->find();
                    $goods_order[] = [
                        'goods_id' => $v['goods_id'],
                        'img' => $sku_info['img'],
                        'name' => $goods_info['name'],
                        'sku_id' => $sku_info['sku_id'],
                        'price' => $sku_info['price'],
                        'count' => $v['count'],
                        'create_time' => $time
                    ];
                }

                //订单主表添加数据
                $order_sn = createOrderSn();
                $order_data = [
                    'user_id' => $user_id,
                    'order_sn' => $order_sn,
                    'pay_order_sn' => $order_sn,
                    'coupon_id' => $coupon_id,
                    'all_price' => $all_price,
                    'freight_price' => $freight_price,
                    'pay_price' => $pay_price,
                    'get_username' => $address_info['username'],
                    'get_mobile' => $address_info['mobile'],
                    'get_province' => getProvinceName($address_info['province_id']),
                    'get_city' => getCityName($address_info['city_id']),
                    'get_area' => getAreaName($address_info['area_id']),
                    'get_address' => $address_info['address'],
                    'up_user_id' => $user_info['up_user_id'],
                    'is_first_order' => $user_info['is_activation'] ? 0 : 1,
                    'is_valid' => $user_info['level'] > 1 ? 1 : 0,
                    'pay_type' => $pay_type,
                    'car_ids' => implode(',', array_column($car_list, 'id')),
                    'create_time' => $time
                ];
                $order_id = Db::name('order')->insertGetId($order_data);

                if ($goods_order) {
                    foreach ($goods_order as &$v) {
                        $v['order_id'] = $order_id;
                    }
                } else {
                    apiReturn(2, '订单信息错误');
                }
                $vice_order_res = Db::name('vice_order')->insertAll($goods_order);

                if ($order_id && $vice_order_res) {
                    // 清除对应购物车商品
                    Db::name('admin_goods_car')->where(['user_id' => $operation_id])->delete();

                    Db::commit();
                    apiReturn(1, '订单生成成功');
                } else {
                    Db::rollback();
                    apiReturn(2, '订单生成失败');
                }
            } else {
                Db::rollback();
                apiReturn(2, '购物车商品数据异常');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试');
        }
    }
}
